<template>
  <el-container class="h-100" v-loading="model.loading">
    <el-header class="shadow-sm d-flex justify-content-center bg-white" style="height: 80px;">
      <div class="w-100" style="line-height: 80px;">
        <h5 class="d-inline">通知公告</h5>
        <div class="float-right" >
          <el-select v-model="isPub" placeholder="请选择" @change="newSearch" size="small" v-permission="[3]">
            <el-option label="接受记录" :value="true"></el-option>
            <el-option label="发布记录" :value="false"></el-option>
          </el-select>
          <el-button @click="dialogVisible = true" type="primary" size="small" v-permission="[1, 3]">发布公告</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="p-2 m-2 bg-white">
      <el-table :data="model.rows">
        <el-table-column fixed label="序号" width="50" align="center">
          <template slot-scope="scope">
            <span>{{scope.$index + (model.pageIndex - 1) * model.pageSize + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="接收人" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ getAccpeter(scope.row.sendNote ? scope.row.sendNote.targetType :
              scope.row.targetType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="公告标题" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.sendNote ? scope.row.sendNote.title :scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center">
          <template slot-scope="scope">
            <span>{{ $formatDateTime(scope.row.sendNote ? scope.row.sendNote.sendTime :
              scope.row.sendTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.count ? '' : 'success'" style="cursor: pointer;" @click="checkRead(scope.row)">
              {{ scope.row.count ? scope.row.sendNote ? scope.row.count + "未读" : '未读' :
              scope.row.sendNote ? "全部已读" : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip content="查看详情" placement="top">
              <i class="el-icon-document" style="font-size: 1.2rem;" @click="checkInfo(scope.row)"></i>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-show="scope.row.sendNote">
              <i class="el-icon-delete ml-3" style="font-size: 1.2rem;" @click="deleteItem(scope.row)"></i>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-show="model.rows.length > 0" class="text-center py-3" @size-change="handleSizeChange"
        @current-change="val => this.model.pageLoad(val)" :current-page="model.pageIndex"
        :page-sizes="[20, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="model.count"></el-pagination>
    </el-main>
    <el-dialog title="发布通知公告" :close-on-click-modal="false" :visible.sync="dialogVisible" @closed="clearRuleForm"
      width="700px">
      <el-dialog width="900px" heigth="600px" title="选择接受区域" :visible.sync="innerVisible"
        :close-on-click-modal="false" @closed="clearInner" append-to-body>
        <div style="height: 600px; overflow: auto;">
          <check-area ref="area"></check-area>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" class="w-200 mr-5" @click="selectedArea()">确认</el-button>
        </div>
      </el-dialog>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <!-- <el-form-item label="已选择的区域" prop="title" >
          <el-button type="text" @click="selectArea">选择区域</el-button>
        </el-form-item>
        <el-form-item label="已选择地市"  v-show="areaDatas[0].names.length > 0">
          {{areaDatas[0].names.toString()}}
        </el-form-item>
        <el-form-item label="已选择区县" v-show="areaDatas[1].names.length > 0">
          {{areaDatas[1].names.toString()}}
        </el-form-item> -->
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="不超过40字"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" prop="context">
          <el-input v-model="ruleForm.context" placeholder="内容不能超过1000字" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <file-upload ref="pathUpload" v-model="ruleForm.fileDatas" :multiple="true">
            <el-button slot="trigger" class="width-200">选取文件</el-button>
            <p class="text-muted d-inline">
              选择文件 支持上传的文件类型: (.jpg .png .rar .txt .zip .doc .ppt
              .xls .pdf .docx .xlsx .pptx)
            </p>
          </file-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')" :loading="model.loading">发布</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="通知公告详情" :close-on-click-modal="false" :visible.sync="detailDeVisible" width="700px">
      <form>
        <div class="form-group row">
          <label class="col-sm-3 col-form-label text-right">接收人</label>
          <div class="col-sm-9 pt-2">
            <span>{{ getAccpeter(row.targetType) }}</span>
          </div>
        </div>
        <div class="form-group row">
          <label class="col-sm-3 col-form-label text-right">接收区域</label>
          <div class="col-sm-9 pt-2">
            <span class="col-form-label">{{ row.receiveAccounts }}</span>
          </div>
        </div>
        <div class="form-group row">
          <label class="col-sm-3 col-form-label text-right">公告标题</label>
          <div class="col-sm-9 pt-2">
            <span class="col-form-label"> {{ row.title }}</span>
          </div>
        </div>
        <div class="form-group row">
          <label class="col-sm-3 col-form-label text-right">内容</label>
          <div class="col-sm-9 pt-2">
            <span class="col-form-label">{{ row.context }}</span>
          </div>
        </div>
        <div class="form-group row" v-viewer>
          <label class="col-sm-3 col-form-label text-right">公告附件</label>
          <div class="col-sm-9 pt-2">
            <ul class="list-unstyled">
              <li v-for="(item, index) in row.fileDatas" :key="index">
                <span>{{ item.fileName }}</span>
                <el-button type="text" class="ml-5" @click="downfile(item)">下载</el-button>
              </li>
            </ul>
          </div>
        </div>
      </form>
    </el-dialog>

    <el-dialog title="公告阅读详情" :visible.sync="readVisible" width="700px">
      <div class="container">
        <div class="row">
          <div class="col">
            <h4>已读</h4>
            <div style="height: 500px;overflow: auto;">
              <p v-for="(item, index) in hasRead" :key="index">
                {{item.cityName}} {{item.areaName}} {{item.name}}({{$getUserType(item.type)}})
              </p>
            </div>

          </div>
          <div class="col">
            <h4>未读</h4>
            <div style="height: 500px;overflow: auto;">
              <p v-for="(item, index) in noRead" :key="index">
                {{item.cityName}} {{item.areaName}} {{item.name}}({{$getUserType(item.type)}})
              </p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

  </el-container>
</template>
<script>
import PagedList from "@/libs/PagedList";
import axios from "axios";
import CheckArea from '@/components/common/CheckArea'
import pca from '@/libs/pca-code'

export default {
  name: "noticelist",
  title: "通知公告列表",
  components: {
    CheckArea
  },
  data() {
    return {
      model: new PagedList("survey/notice/getNotice", 20),
      dialogVisible: false,
      detailDeVisible: false,
      readVisible: false,
      innerVisible: false,
      areaDatas: [{ codes: [], names: [] }, { codes: [], names: [] }],
      isPub: true,
      row: {},
      ruleForm: {
        title: "",
        context: "",
        targetType: 7,
        fileDatas: []
      },
      rules: {
        title: [
          { required: true, message: "请输入公告名称", trigger: "blur" },
          { max: 40, message: "公告标题不能超过40字符", trigger: "blur" },
        ],
        context: [
          { required: true, message: "请输入公告内容", trigger: "blur" },
          { max: 1000, message: "公告内容不能超过1000字符", trigger: "blur" }
        ]
      },
      // 已读
      hasRead: [],
      // 未读
      noRead: []
    };
  },
  mounted() {
    this.newSearch();
  },
  methods: {
    newSearch() {
      if (this.isPub) {
        this.model.url = 'survey/notice/getNotice'
      } else {
        this.model.url = 'survey/notice/getCityNotice'
      }
      this.model.search();
    },
    handleSizeChange(pageSize) {
      this.model.pageSize = pageSize;
      this.newSearch();
    },
    // 查看详情
    checkInfo(row) {
      this.row = row.sendNote || row;
      this.detailDeVisible = true;
    },
    // 删除
    deleteItem(row) {
      this.$confirm(`确认删除 ${row.sendNote.title} ?`, "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          axios
            .delete(`survey/notice/delete?id=${row.sendNote.id}`)
            .then(res => {
              console.log(res);
              if (res.data.code === "200") {
                this.$message({
                  message: "删除成功",
                  type: "success"
                });
                this.newSearch();
              } else {
                this.$codeError(res);
              }
            })
            .catch(error => {
              this.$catchError(error);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 暂时不支持区域选择,所以暂时写死
          // 暂时不支持区域选择,所以暂时写死
          let obj = {}
          if (this.$store.getters.userType === 1) {
            let areaIds = [610102, 610103, 610104, 610111, 610112, 610113, 610114, 610115, 610116, 610117, 610118, 610122, 610124, 610202, 610203, 610204, 610222, 610302, 610303, 610304, 610322, 610323, 610324, 610326, 610327, 610328, 610329, 610330, 610331, 610402, 610403, 610404, 610422, 610423, 610424, 610425, 610426, 610428, 610429, 610430, 610431, 610481, 610482, 610502, 610503, 610522, 610523, 610524, 610525, 610526, 610527, 610528, 610581, 610582, 610602, 610603, 610621, 610622, 610623, 610625, 610626, 610627, 610628, 610629, 610630, 610631, 610632, 610702, 610703, 610722, 610723, 610724, 610725, 610726, 610727, 610728, 610729, 610730, 610802, 610803, 610822, 610824, 610825, 610826, 610827, 610828, 610829, 610830, 610831, 610881, 610902, 610921, 610922, 610923, 610924, 610925, 610926, 610927, 610928, 610929, 611002, 611021, 611022, 611023, 611024, 611025, 611026]
            let cityIds = [610100, 610200, 610300, 610400, 610500, 610600, 610700, 610800, 610900, 611000]
            obj = {
              data: JSON.stringify(this.ruleForm),
              cityIds: cityIds.toString(),
              areaIds: areaIds.toString()
            }
          } else {
            obj = {
              data: JSON.stringify(this.ruleForm),
              areaIds: Object.keys(pca[this.$store.getters.cityId]).toString()
            }
          }
          this.model.loading = true;
          this.$post("survey/notice/addNotice", obj)
            .then(res => {
              this.$message({
                message: this.ruleForm.id ? "修改成功" : "发布成功",
                type: "success"
              });
              this.dialogVisible = false;
              this.newSearch();
            })
            .finally(() => {
              this.model.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    getAccpeter(deFlag) {
      let str = "";
      if (deFlag == 1) {
        str = "县级用户";
      } else if (deFlag == 2) {
        str = "市级用户";
      } else if (deFlag == 3) {
        str = "市级用户,县级用户";
      } else if (deFlag == 4) {
        str = "业务审核员";
      } else if (deFlag == 5) {
        str = "业务审核员,县级用户";
      } else if (deFlag == 6) {
        str = "业务审核员,市级用户";
      } else if (deFlag == 7) {
        str = "业务审核员,市级用户,县级用户";
      }
      return str;
    },
    clearRuleForm() {
      // 清空附件
      this.$refs.pathUpload.clearFiles();
      this.ruleForm = {
        title: "",
        context: "",
        targetType: 7,
        fileDatas: []
      };
      this.areaDatas = [{ codes: [], names: [] }, { codes: [], names: [] }]
      this.$refs.ruleForm.resetFields();
    },
    downfile(item) {
      this.$exportExcel(
        `survey/file/downloadFile?fileUrl=${item.filePath}&fileName=${
        item.fileName
        }&oauth=${this.$store.state.user.user.oauth}`
      );
    },
    // 查看已读未读
    checkRead(row) {
      if (!row.sendNote) {
        return
      }
      this.model.loading = true
      this.hasRead = []
      this.noRead = []
      this.$get('survey/notice/getNoticeReadStart', { id: row.sendNote.id }).then(res => {
        res.data.data.forEach(item => {
          if (item.state) {
            this.hasRead.push(item)
          } else {
            this.noRead.push(item)
          }
        })
        this.readVisible = true
      }).finally(() => {
        this.model.loading = false
      })
    },
    selectArea() {
      this.innerVisible = true
      if (this.areaDatas[1] && this.areaDatas[1].codes && this.areaDatas[1].codes.length > 0) {
        this.$refs.area.setData([], this.areaDatas[1].codes)
      }
    },
    selectedArea() {
      let datas = this.$refs.area.getAllData()
      this.areaDatas = [{ codes: [], names: [] }, { codes: [], names: [] }]
      this.areaDatas[0]['codes'].push(...(datas[0]['codes']))
      this.areaDatas[0]['names'].push(...(datas[0]['names']))
      this.areaDatas[1]['codes'].push(...(datas[1]['codes']))
      this.areaDatas[1]['names'].push(...(datas[1]['names']))
      this.innerVisible = false
    },
    clearInner() {
      this.$refs.area.clearDatas()
    }
  }
};
</script>
<style lang='scss'>
</style>